package com.qingke.easyjava.jdbc.command.impl;

import java.util.regex.Pattern;

import com.qingke.easyjava.jdbc.app.BeSuperApplication;
import com.qingke.easyjava.jdbc.app.BeSuperDao;
import com.qingke.easyjava.jdbc.command.SystemCommand;
import com.qingke.easyjava.jdbc.pojo.Player;
import com.qingke.easyjava.jdbc.util.QingkeConsole;

public class SignCommand extends SystemCommand  {

    @Override
    public void execute() {
        BeSuperDao dao = new BeSuperDao();
        
        String username = QingkeConsole.askUserInput("请输入用户名");
        // check username 
        while (dao.isUsernameExists(username)) {
            QingkeConsole.println("用户名已存在！");
            username = QingkeConsole.askUserInput("请输入用户名");
        }
        
        String password = null;
        while (true) {
            password = QingkeConsole.askUserInput("请输入密码");
            try {
                // validate password
                validatePassword(password);
                break;
            } catch (Exception e) {
                QingkeConsole.println("密码格式不对！" + e.getMessage());
                continue;
            }
        }
        
        String nickname = QingkeConsole.askUserInput("请输入昵称");

        Player player = dao.signup(username, password, nickname);
        BeSuperApplication.getInstance().setPlayerProfile(player);
    }
    
    private void validatePassword(String password) throws Exception {
        // 1. length >= 6
        Pattern lenPattern = Pattern.compile("[0-9a-zA-Z]{6,}");
        if (!lenPattern.matcher(password).find()) {
            throw new Exception("密码长度必需大于等于6位");
        }
        
        // 2. not all number
        Pattern numPattern = Pattern.compile("[0-9]");
        if (!numPattern.matcher(password).find()) {
            throw new Exception("密码至少需要含有一位数字");
        }
        
        // 3. not all word
        Pattern wordPattern = Pattern.compile("[a-zA-Z]");
        if (!wordPattern.matcher(password).find()) {
            throw new Exception("密码至少需要含有一位字母");
        }
    }
}
